/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package webservices;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Val
 */
public abstract class AbstractWebService {
     
    private static Object parse(String url,String xpathurl, QName dataType) throws ParserConfigurationException, XPathExpressionException {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        Object result = null;
        XPathExpression expr = null;
        Document doc = null;

        try {
            doc = builder.parse(url);

            XPathFactory factory = XPathFactory.newInstance();

            XPath xpath = factory.newXPath();
            expr = xpath.compile(xpathurl);

            result = expr.evaluate(doc, dataType);
        }
        catch(SAXException ex) {
            Logger.getLogger(AbstractWebService.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch(IOException ex) {
            Logger.getLogger(AbstractWebService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public static NodeList parseNodeList(String url,String xpathurl) throws ParserConfigurationException, XPathExpressionException {
        return (NodeList) parse(url, xpathurl, XPathConstants.NODESET);
    }
    public static String parseString(String url,String xpathurl) throws ParserConfigurationException, XPathExpressionException {
        return (String) parse(url, xpathurl, XPathConstants.STRING);
    }
    public static int parseNumber(String url,String xpathurl) throws ParserConfigurationException, XPathExpressionException {
        return (Integer) parse(url, xpathurl, XPathConstants.NUMBER);
    }
}
